<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>通过 阿里--高德地图 获取距离</title>

  <style type="text/css">
        html,body{
          width: 100%;
          height: 100%;
          box-sizing: border-box;
        }
        #demo{
           border: 1px solid #000;
           padding: 10px;
          margin: 10px;
        }
      #aliMap{
        border: 1px solid #000;
        height: 400px;
        margin: 10px;
      }
  </style>

  <script type="text/javascript" src="./jquery.js"></script>
  <script type="text/javascript" src="./excelTable.js"></script>


  <script src="./xlsx.full.min.js"></script>


  <link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
  <script src="http://cache.amap.com/lbs/static/es5.min.js"></script>
  <script src="http://webapi.amap.com/maps?v=1.3&key=d6ded2f3c4f8a7439fb24b222c980329"></script>
  <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.10"></script>


</head>
<body>
      <input type="file" onchange="importf(this)" />

      <a href="#" id ='downloadExcel' >导出Excel文件</a>

        <table id="table_b">
          <tr>
            <th>出发地</th>
            <th>目的地</th>
            <th>运输距离</th>
          </tr>
        </table>

      <div onclick="test()">点击</div>

      <div id="demo">Excel内容将在这里呈现</div>

      <div id="aliMap"></div>

      <table id="table_a">
        <tr>
          <th>出发地</th>
          <th>目的地</th>
          <th>运输距离</th>
        </tr>
      </table>

<script>

      function test(){
            $.get('http://restapi.amap.com/v3/geocode/geo?key=001950ab40ada48bb6fbc389ab70f2e8&address=南昌青云谱区井岗山大道150号&city=',function(res){
                console.log(res.geocodes[0].location.split(','));
            })

      }

     $('#downloadExcel').ExportExcel('table_a');
  /*
  FileReader共有4种读取方法：
  1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
  2.readAsBinaryString(file)：将文件读取为二进制字符串
  3.readAsDataURL(file)：将文件读取为Data URL
  4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
               */
  var wb;//读取完成的数据
  var rABS = false; //是否将文件读取为二进制字符串

//  定义一个全局查询计数变量；
   var  hasSearchedCount = 0;
   var  searchLength = 0;
   var  tempResult = '';

  //   定义一个地图
  var map = new AMap.Map('aliMap', {
    resizeEnable: true,
    zoom:5,
    center: [116.397428, 39.90923]
  });
  window.driving0 = '';
      // // 规划路线
      AMap.plugin('AMap.Driving',function() {
        window.driving0 = new AMap.Driving({
          map: map
        });
      });

//   通过地址获取相应的距离

      function getDistance(sPlace,ePlace,index){

              let sCity = '';
              let eCity = '';

//          定义查询结果状态
              let resObj = {
                    stu : '',
                    res : ''
                  };


//          获取地点对应的市区
              sPlace?sCity=sCity.slice(0,2):'';
              ePlace?eCity=eCity.slice(0,2):'';

//        定义查询对象
              let searchObj = [
                    {keyword : sPlace, city :'南昌'},
                    {keyword : ePlace, city : '南昌'}
              ];

              let searchArr =[];
              let location = 'http://restapi.amap.com/v3/geocode/geo?key=001950ab40ada48bb6fbc389ab70f2e8&address=南昌青云谱区井岗山大道150号&city=';
//              let location = 'http://restapi.amap.com/v3/geocode/geo?key=001950ab40ada48bb6fbc389ab70f2e8&address='+sPlace+'&city=';

            let  locationB ='http://restapi.amap.com/v3/place/text?s=rsv3&children=&key=8325164e247e15eea68b59e89200988b&page=1&offset=10&city=440300&language=zh_cn&callback=jsonp_72950_&platform=JS&logversion=2.0&sdkversion=1.3&appname=http%3A%2F%2Flbs.amap.com%2Fconsole%2Fshow%2Fpicker&csid=F9A886D4-2E0F-405D-A909-0A09D76BFDEB&keywords='+sPlace;

              $.get(locationB,function(res){
                debugger
                  searchArr.push(res.geocodes[0].location.split(','));

                let locationA = 'http://restapi.amap.com/v3/geocode/geo?key=001950ab40ada48bb6fbc389ab70f2e8&address='+ePlace+'&city=';
                 $.get(locationA,function(res){
                      searchArr.push(res.geocodes[0].location.split(','));

                   // // 规划路线
//                   AMap.plugin('AMap.Driving',function(){
//                     var driving0  = new AMap.Driving({
//                       map : map
//                     });
                     driving0.search(searchArr[0],searchArr[1],function(status,result){

                       // console.log(result);
                       if( hasSearchedCount ==18){
                         console.log('---->',tempResult[hasSearchedCount]);
                         console.log('---->',searchArr);
                         console.log('---->', result);
                       }

                       if( status = 'complete'){

                         if(!result.routes){
                           tempResult[hasSearchedCount].distance = result.info;
                         } else {
                           tempResult[hasSearchedCount].distance = result.routes[0].distance/1000 +' km';
                         }
//                      tempResult[hasSearchedCount].distance = result.routes[0].distance;
                         hasSearchedCount++;    //搜索到一条数据
                         console.log('已经查处:'+ hasSearchedCount+'---status为:'+status+'---info:'+ result.info+'---总长度为:'+ searchLength);

                         if(window.hasSearchedCount == window.searchLength){    //判断是否查询完毕
                           console.log('最终的查询结构',JSON.stringify(tempResult));

//                            生成表格
                           let   tempTable = document.getElementById('table_a');
                           let   str = '';
                           for(let k = 0; k < tempResult.length; k++ ){
                             str += '<tr>';
                             for(let key in tempResult[k] ){
                               str+='<td>'+tempResult[k][key]+'</td>'
                             }
                             str+='</tr>';

                           }
                           $('#table_a').append(str);

                         }  else {


                         }

                       } else {
                         console.log('此条路线搜索出现异常')
                       }

                       resObj.stu = status;
                       resObj.res = result;

                       //   status ： complete 时搜索到规划路线
                       //    result :  有具体的线路规划方案
                     });
                   });

                 });
//              });

             // console.log('查询对象:'+JSON.stringify(searchObj));



         return resObj;

      }
//   let test_res =  getDistance('南昌北郊新祺周桑海北路139','南昌市南昌县小蓝经济开发区振铃东路1号');
//      console.log('测试输出结果',test_res );

  function importf(obj) {//导入
    if(!obj.files) {
      return;
    }

//    初始化查询参数
      hasSearchedCount = 0;
      searchLength = 0;
      tempResult ='';



    var f = obj.files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      var data = e.target.result;
      if(rABS) {
        wb = XLSX.read(btoa(fixdata(data)), {//手动转化
          type: 'base64'
        });
      } else {
        wb = XLSX.read(data, {
          type: 'binary'
        });
      }
      //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
      //wb.Sheets[Sheet名]获取第一个Sheet的数据
      var my_data =  XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

      tempResult =  my_data;
      searchLength = my_data.length;

//      调用阿里云接口查询距离
      for(let i =0; i<my_data.length;i++){
          let temp = [];
          for(let key in my_data[i]){
              temp.push(my_data[i][key])
          }

        getDistance(temp[0],temp[1]);    // 查询距离

      }

//      console.log('原始数据:',my_data);
//      console.log('原始数据:',JSON.stringify( my_data ));


//     展示已导入数据
      let   str_fs = '';
      for(let k = 0; k < my_data.length; k++ ){
        str_fs += '<tr>';
        for(let key in my_data[k] ){
          str_fs+='<td>'+ my_data[k][key]+'</td>'
        }
        str_fs+='</tr>';

      }

//      $('#table_b').append(str_fs);

//      document.getElementById("demo").innerHTML= JSON.stringify( my_data );

    };
    if(rABS) {
      reader.readAsArrayBuffer(f);
    } else {
      reader.readAsBinaryString(f);
    }
  }

  function fixdata(data) { //文件流转BinaryString
    var o = "",
      l = 0,
      w = 10240;
    for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
    return o;
  }

//

</script>
</body>
</html>
